﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;

namespace NHTrace
{
  public class Config
  {
    public Config(System.Configuration.Configuration config)
    {
      _config = config;

      TemplatePath = config.AppSettings.Settings["templatePath"].Value;
      LogCharSize = int.Parse(config.AppSettings.Settings["logCharSize"].Value);

      int aux;
      if (int.TryParse(config.AppSettings.Settings["messagesRefreshTimeInMilliseconds"].Value, out aux))
        MessagesRefreshTimeInMilliseconds = aux;
      else
        MessagesRefreshTimeInMilliseconds = 1000;
      
      LogEnabled = bool.Parse(config.AppSettings.Settings["logEnabled"].Value);
      ShowSatusbar = bool.Parse(config.AppSettings.Settings["showStatusBar"].Value);
      ShowProcess = bool.Parse(config.AppSettings.Settings["showProcess"].Value);
      AlwaysOnTop = bool.Parse(config.AppSettings.Settings["alwaysOnTop"].Value);

      //string sinkName = config.AppSettings.Settings["sinkName"].Value;
      //int port = int.Parse(config.AppSettings.Settings["port"].Value);
      //receiverParameters.Add("sinkName", sinkName);
      //receiverParameters.Add("port", port);
      //<add key="sinkName" value="LoggingSink"/>
      //<add key="port" value="7070"/>

      ReceiverType = config.AppSettings.Settings["receiverType"].Value;

      string[] receiverTypeParts = ReceiverType.Split(new char[1]{','});

      foreach (var key in config.AppSettings.Settings.AllKeys)
      {
        if (key.StartsWith(receiverTypeParts[0]))
        {
          var keyAux = key.Remove(0, (receiverTypeParts[0] + ".").Length);
          _receiverParameters.Add(keyAux, config.AppSettings.Settings[key].Value);
        }
      }
    }

    public string TemplatePath { get; private set; }

    public int LogCharSize { get; private set; }

    public bool LogEnabled { get; set; }

    public bool ShowSatusbar { get; set; }

    public bool ShowProcess { get; set; }

    public bool AlwaysOnTop { get; set; }

    public string ReceiverType { get; private set; }

    public int MessagesRefreshTimeInMilliseconds { get; private set; }

    private Dictionary<string, string> _receiverParameters = new Dictionary<string, string>();
    public Dictionary<string, string> ReceiverParameters
    {
      get
      {
        return new Dictionary<string,string>(_receiverParameters);
      }
    }

    private System.Configuration.Configuration _config;

    public void Save()
    {
      _config.AppSettings.Settings["logEnabled"].Value = LogEnabled.ToString();
      _config.AppSettings.Settings["showStatusBar"].Value = ShowSatusbar.ToString();
      _config.AppSettings.Settings["showProcess"].Value = ShowProcess.ToString();
      _config.AppSettings.Settings["alwaysOnTop"].Value = AlwaysOnTop.ToString();
      _config.Save();
    }
  }
}
